#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <string.h>
#include <algorithm>

using namespace std;
using std::cout;
using std::endl;
using std::string;
using std::vector;

struct Record
{
    Record(const string & word,int frequency)
    :_word(word)
    ,_frequency(frequency)
    {}

    string _word;
    int _frequency;
};

bool operator<(const Record & lhs,const Record & rhs){
    return lhs._word < rhs._word;
}

class Dictionary
{
public:

    Dictionary(int capacity)
    {
        _dict.reserve(capacity);
    }

    void read(const std::string &filename){
        ifstream ifs(filename);
        if(!ifs){
            cerr << "ifs open file failed" << endl;
            return;
        }

        string line;
        while(getline(ifs,line)){
            istringstream iss(line);
            string word;
            while(iss >> word){
                string newword = dealword(word);
                insert(newword);
            }
        }

        sort(_dict.begin(),_dict.end());

        ifs.close();
    }

    string dealword(const string & word){
        for(size_t idx = 0;idx != word.size(); ++idx){
            if(!isalpha(word[idx])){
                return string();
            }
        }
        return word;
    }
    
    void insert(const string & word){
        if(word == string()){
            return;
        }

        size_t idx = 0;
        for(;idx != _dict.size();++idx){
            if(word == _dict[idx]._word){
               ++_dict[idx]._frequency;
               break;
            }
        }
        if(idx == _dict.size()){
            _dict.push_back(Record(word,1));
        }
    }

    void store(const std::string &filename){
        ofstream ofs(filename);
        if(!ofs){
            cerr << "ofs open file failed" << endl;
            return;
        }
        for(size_t idx = 0;idx != _dict.size();++idx){
            ofs << _dict[idx]._word << " " << _dict[idx]._frequency << endl;
        }

        ofs.close();
    }

private:
    vector<Record> _dict;
};


void test0(){   
    Dictionary dict(10000);
    dict.read("The_Holy_Bible.txt");
    dict.store("dict.dat");
}

int main(int argc, char * argv[])
{
    test0();
    return 0;
}


